﻿<%@ WebHandler Language="C#" Class="LoginCenter" Debug="true" %>
using System;
using System.Web;
using System.Text;
using System.Data;
using System.Collections.Generic;
using System.Web.SessionState;
using FaceOZ.Data;
//using NLog;
using TrackMoney;
using TrackMoney.EmailTemp;
public class LoginCenter : IHttpHandler, IRequiresSessionState 
{
    //private static Logger logger = LogManager.GetCurrentClassLogger();
    public void ProcessRequest (HttpContext context) 
    {
        if (context.Request["mode"] != null)
        {
            int pagesize = Convert.ToInt32(context.Request["rows"]);//current line number
            int pagenum = Convert.ToInt32(context.Request["page"]);//current page
            string mode =  context.Request["mode"].ToString();
            switch(mode)
            {
                case "signup":
                    signup(context);
                    break;
                case "login":
                    break;
                case "forgotpassword":
                    break;
                case "fetchId":
                    fetchId(context);
                    break;
                case "CheckEmail":
                    fetchId(context);
                    break;
                case "VerifyLogin":
                    VerifyLogin(context);
                    break;
                case "fetchData":
                    fetchData(context);
                    break;
                
                case "Logout":
                    Logout(context);
                    break;
                case "ForgotPassword":
                    ForgotPassword(context);
                    break;
                case "SendEmail":
                    SendEmail(context);
                    break;
                case "ResetPassword":
                    ResetPassword(context);
                    break;
                case "test":
                    CaseElse(context);
                    break;
            }
        }
    }
    /// <summary>
    /// Reset the password
    /// </summary>
    /// <param name="context"></param>
    private void ResetPassword(HttpContext context)
    {
        bool bRet = false;
        string email = context.Request["id"].ToString();
        string p = context.Request["p"].ToString();
        bRet = Login.UpdatePassword(email, p);
        context.Response.Write(bRet.ToString());
    }
    /// <summary>
    /// Send an Email 
    /// </summary>
    /// <param name="context"></param>
    private void SendEmail(HttpContext context)
    {
        string result = "";
        try
        {
            string email = context.Request["id"].ToString();
            string title = "Reset the password -- Money Tracker";
            string code = context.Request["code"].ToString();
            string url = HttpContext.Current.Request.Url.Host;
            string urlReset = "http://" + url + "/Login/Login.htm?mode=resetpassword&code="+ email + "|" + code;
            string content = string.Format(TrackMoney.EmailTemp.ForgotPassword.emailForgotPassword, urlReset);
            
            MailService.SendEMail(content, email, title);
            result = "1";
        }
        catch
        {
            result = "0";
        }
        finally
        {
            context.Response.Write(result);
        }
    }
    /// <summary>
    /// if existing email, send an email; otherwise, prompt an error
    /// </summary>
    /// <param name="context"></param>
    private void ForgotPassword(HttpContext context)
    {
        string code = context.Request["code"].ToString();
        string email = context.Request["id"].ToString();

        int id = Login.FetchId(email);

        Result ret = new Result();
        ret.ret = (id == 0) ? false : true;
        if (!ret.ret)
        {
            ret.str = "There is not an Email on record for your user name";
        }
        context.Response.Write(Login.ConvertResultToJson(ret).ToString());
    }
    /// <summary>
    /// Error input
    /// </summary>
    /// <param name="context"></param>
    private void CaseElse(HttpContext context)
    {
        context.Response.Write("Error Parameter");
    }
    private void Logout(HttpContext context)
    {
        //App.appData.SessionID = 0;
        context.Session["ID"] = 0;
        HttpCookie aCookie;
        string cookieName;
        int limit = context.Request.Cookies.Count;
        for (int i = 0; i < limit; i++)
        {
            cookieName = context.Request.Cookies[i].Name;
            aCookie = new HttpCookie(cookieName);
            aCookie.Expires = DateTime.Now.AddDays(-1);
            context.Response.Cookies.Add(aCookie);
        }
        context.Response.Write(int.Parse(context.Session["ID"].ToString()));
    }
    
    /// <summary>
    /// get the data in the cookies
    /// </summary>
    /// <param name="context"></param>
    private void fetchData(HttpContext context)
    {
        string email = "", p = "";
        try
        {
            HttpCookie cookie = context.Request.Cookies["login"];
            email = cookie.Values["UserID"];
            p = cookie.Values["Password"];
        }
        catch
        {
            email = "";
            p = "";
        }
        context.Response.Write(email + '|' + p);
    }
    
    /// <summary>
    /// verify the login
    /// </summary>
    /// <param name="context"></param>
    private void VerifyLogin(HttpContext context)
    {
        string u = context.Request["email"].ToLower();
        string p = context.Request["p"];
        bool r = bool.Parse(context.Request["checked"]);
        string o = context.Request["o"];
        string psd = Login.FetPassword(u);
        if ((psd == p) && (r))
        {
            //save everything to the cookies
            HttpCookie c = new HttpCookie("login");
            c.Values.Add("UserID", u);
            c.Values.Add("Password", o);
            DateTime dtNow = DateTime.Now;
            TimeSpan tsMinute = new TimeSpan(7, 0, 0, 0);
            c.Expires = dtNow + tsMinute;
            context.Response.Cookies.Add(c);
        }
        context.Response.Write((psd == p).ToString());
    }
    /// <summary>
    /// sign up
    /// </summary>
    /// <param name="context"></param>
    private void signup(HttpContext context)
    {

        string record = context.Request["record"];
        string[] r = record.Split('|');
        UserAccount ac = new UserAccount();
        //$('#idName').val() + '|' + $('#idEmail').val() + '|' + $('#idGender').val() + '|' + $('#idAge').val() + hex_md5($('#idPassword').val());
        ac.name = r[0];
        ac.email = r[1].ToLower();
        ac.gender = (r[2] =="") ? 0:int.Parse(r[2]);
        ac.age = (r[3] == "") ? 30 : int.Parse(r[3]);
        ac.password = r[4];
        bool bRet = Login.SaveSignUp(ac);
        context.Response.Write(bRet.ToString());
    }
    /// <summary>
    /// Fetch the user id according to registered email
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private void fetchId(HttpContext context)
    {
        string email = context.Request["email"].ToLower();
        int id = Login.FetchId(email);
        //context.Session["id"] = id.ToString();
        //App.appData.SessionID = id;
        context.Session["ID"] = id;
        context.Response.Write(id.ToString()) ;
    }

    
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}